from usr.modbus_slave import ModbusSlave
from usr.tcpclient import TcpClient
import _thread
import utime

SERVER_HOST = '47.94.219.157'
SERVER_PORT = 9994

class ModbusService:
    def __init__(self, modbus):
        self.__modbus = modbus
        self.__client = TcpClient()
        self.__client.set_timeout(60)
        self.__client.on_connect = self.on_connect
        self.__thread = None

    def __del__(self):
        self.stop()
        del self.__client

    def start(self):
        self.__thread = _thread.start_new_thread(self.on_execute, ())

    def stop(self):
        if self.__thread != None:
            self.__thread.stop_thread(self.__thread)
            self.__thread = None


    def on_connect(self):
        regpack = b'\x7B13900000001\x7B'
        self.__client.send(regpack)

    def on_execute(self):
        """响应Modbus指令
        """
        try:
            self.__client.connect(SERVER_HOST, SERVER_PORT)
        except Exception:
            pass
        while True:
            try:
                if not self.__client.connected:
                    utime.sleep(30)
                    print('断开重连')
                    self.__client.connect(SERVER_HOST, SERVER_PORT)
                    utime.sleep(1)
                if not self.__client.connected:
                    continue
                #print('等待数据')
                data = self.__client.receive()
                #print(data)
                if data != None:
                    _, resp  = self.__modbus.parse(data)
                    #print(resp)
                    if resp != None:
                        self.__client.send(resp)
                        del resp
            except Exception as e:
                print(e)